// DOM元素
const addForm = document.getElementById('addForm');
const nameInput = document.getElementById('nameInput');
const nameList = document.getElementById('nameList');
const clearBtn = document.getElementById('clearBtn');

// 从本地存储获取名单
function getNames() {
    const names = localStorage.getItem('names');
    return names ? JSON.parse(names) : [];
}

// 保存名单到本地存储
function saveNames(names) {
    localStorage.setItem('names', JSON.stringify(names));
}

// 显示名单
function displayNames() {
    const names = getNames();
    nameList.innerHTML = '';
    
    if (names.length === 0) {
        nameList.innerHTML = '<li>暂无人员</li>';
        return;
    }
    
    names.forEach((name, index) => {
        const li = document.createElement('li');
        
        const nameSpan = document.createElement('span');
        nameSpan.textContent = name;
        
        const deleteBtn = document.createElement('button');
        deleteBtn.innerHTML = '×';
        deleteBtn.className = 'delete-btn';
        deleteBtn.addEventListener('click', () => deleteName(index));
        
        li.appendChild(nameSpan);
        li.appendChild(deleteBtn);
        nameList.appendChild(li);
    });
}

// 添加新人员
function addName(event) {
    event.preventDefault();
    
    const name = nameInput.value.trim();
    if (!name) return;
    
    const names = getNames();
    names.push(name);
    saveNames(names);
    
    nameInput.value = '';
    displayNames();
    
    // 添加动画效果
    const lastItem = nameList.lastElementChild;
    lastItem.style.animation = 'fadeIn 0.5s ease';
}

// 删除人员
function deleteName(index) {
    const names = getNames();
    names.splice(index, 1);
    saveNames(names);
    displayNames();
}

// 清空名单
function clearNames() {
    if (confirm('确定要清空所有人员吗？')) {
        localStorage.removeItem('names');
        displayNames();
    }
}

// 事件监听
addForm.addEventListener('submit', addName);
clearBtn.addEventListener('click', clearNames);

// 页面加载时显示名单
window.addEventListener('load', displayNames); 